#include "mduserhandle.h"
#include "logger.h"
#include <unistd.h>
using json = nlohmann::json;

CMduserHandler::CMduserHandler(const std::string& brokerID, 
                             const std::string& userID, 
                             const std::string& password,
                             const std::string& flow_path,
                             const std::string& front_address) 
    : m_mdApi(nullptr),
      m_brokerID(brokerID),
      m_userID(userID),
      m_password(password),
      m_flow_path(flow_path),
      m_front_address(front_address),
      m_tcp_server(nullptr)
{
}

CMduserHandler::~CMduserHandler()
{
    if (m_mdApi)
    {
        m_mdApi->Release();
        m_mdApi = nullptr;
    }
}

void CMduserHandler::connect()
{
    Logger::info("开始连接行情服务器");
    // 创建并初始化API
    m_mdApi = CThostFtdcMdApi::CreateFtdcMdApi(m_flow_path.c_str(), true, true);
    m_mdApi->RegisterSpi(this);
    char* front_address = const_cast<char*>(m_front_address.c_str());
    m_mdApi->RegisterFront(front_address);
    m_mdApi->Init();
}

void CMduserHandler::login()
{
    Logger::info("开始登录行情服务器");
    CThostFtdcReqUserLoginField t = {0};
    while (m_mdApi->ReqUserLogin(&t, nRequestID++)!=0) sleep(1);
}

void CMduserHandler::subscribe(const std::string& instrument)
{
    // 创建一个字符数组指针数组
    char* ppInstrumentID[] = { const_cast<char*>(instrument.c_str()) };
    
    // 订阅行情
    int result = m_mdApi->SubscribeMarketData(ppInstrumentID, 1);
    
    if(result == 0) {
        Logger::info("订阅行情请求发送成功: " + instrument);
    } else {
        Logger::error("订阅行情请求发送失败: " + instrument + ", 错误码: " + std::to_string(result));
    }
}

void CMduserHandler::unsubscribe(const std::string& instrument)
{
    // 创建一个字符数组指针数组
    char* ppInstrumentID[] = { const_cast<char*>(instrument.c_str()) };
    
    // 取消订阅行情
    int result = m_mdApi->UnSubscribeMarketData(ppInstrumentID, 1);
    if(result == 0) {
        Logger::info("取消订阅行情请求发送成功: " + instrument);
    } else {
        Logger::error("取消订阅行情请求发送失败: " + instrument + ", 错误码: " + std::to_string(result));
    }
}

void CMduserHandler::release()
{
    if (m_mdApi)
    {
        m_mdApi->Release();
        m_mdApi = nullptr;
    }
}

void CMduserHandler::OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData)
{
    if(m_tcp_server != nullptr) {
        try {
            json market_data;
            market_data["type"] = "market_data";
            
            if (pDepthMarketData == nullptr) {
                market_data["data"] = nullptr;
            } else {
                market_data["data"] = {
                    {"TradingDay", pDepthMarketData->TradingDay},
                    {"InstrumentID", pDepthMarketData->InstrumentID},
                    {"ExchangeID", pDepthMarketData->ExchangeID},
                    {"LastPrice", pDepthMarketData->LastPrice},
                    {"PreSettlementPrice", pDepthMarketData->PreSettlementPrice},
                    {"PreClosePrice", pDepthMarketData->PreClosePrice},
                    {"PreOpenInterest", pDepthMarketData->PreOpenInterest},
                    {"OpenPrice", pDepthMarketData->OpenPrice},
                    {"HighestPrice", pDepthMarketData->HighestPrice},
                    {"LowestPrice", pDepthMarketData->LowestPrice},
                    {"Volume", pDepthMarketData->Volume},
                    {"Turnover", pDepthMarketData->Turnover},
                    {"OpenInterest", pDepthMarketData->OpenInterest},
                    {"ClosePrice", pDepthMarketData->ClosePrice},
                    {"SettlementPrice", pDepthMarketData->SettlementPrice},
                    {"UpperLimitPrice", pDepthMarketData->UpperLimitPrice},
                    {"LowerLimitPrice", pDepthMarketData->LowerLimitPrice},
                    {"UpdateTime", pDepthMarketData->UpdateTime},
                    {"UpdateMillisec", pDepthMarketData->UpdateMillisec},
                    {"BidPrice1", pDepthMarketData->BidPrice1},
                    {"BidVolume1", pDepthMarketData->BidVolume1},
                    {"AskPrice1", pDepthMarketData->AskPrice1},
                    {"AskVolume1", pDepthMarketData->AskVolume1}
                };
            }
            
            // 发送数据给客户端
            m_tcp_server->broadcast(market_data.dump());
            Logger::info("行情数据发送成功: " + market_data.dump());
        } catch (const std::exception& e) {
            Logger::error("发送行情数据时发生错误: " + std::string(e.what()));
        }
    }
    else {
        Logger::error("m_tcp_server为nullptr");
    }
}

void CMduserHandler::setServer(TcpServer* server)
{
    m_tcp_server = server;
} 

void CMduserHandler::OnFrontConnected()
{
    Logger::info("OnFrontConnected");
    // m_connected = true;
    login();
}

void CMduserHandler::OnFrontDisconnected(int nReason)
{
    Logger::info("OnFrontDisconnected");
    Logger::info("nReason: " + std::to_string(nReason));
    // m_connected = false;
    sleep(1);  // 等待1秒后重新连接
    connect();
}
